﻿/*
* CRM_invoice.cs
*
* 功 能： N/A
* 类 名： CRM_invoice
*
* Ver    变更日期             负责人     变更内容
* ───────────────────────────────────
* V1.0  2015-06-23 18:38:21    黄润伟    
*
* Copyright (c) 2015 www.xhdcrm.com   All rights reserved.
*┌──────────────────────────────────┐
*│　版权所有：黄润伟                      　　　　　　　　　　　　　　│
*└──────────────────────────────────┘
*/

using System;
using System.Data;
using System.Web;
using XHD.Common;
using XHD.Controller;

namespace XHD.Server
{
    public class CRM_invoice
    {
        public static BLL.CRM_invoice invoice = new BLL.CRM_invoice();
        public static Model.CRM_invoice model = new Model.CRM_invoice();

        public HttpContext Context;
        public int emp_id;
        public string emp_name;
        public Model.hr_employee employee;
        public HttpRequest request;
        public string uid;


        public CRM_invoice()
        {
        }

        public CRM_invoice(HttpContext context)
        {
            Context = context;
            request = context.Request;

            var userinfo = new User_info();
            employee = userinfo.GetCurrentEmpInfo(context);

            emp_id = employee.ID;
            emp_name = PageValidate.InputText(employee.name, 50);
            uid = PageValidate.InputText(employee.uid, 50);
        }

        public void save()
        {
            model.invoice_num = PageValidate.InputText(request["T_invoice_num"], 255);
            string orderid = PageValidate.InputText(request["orderid"], 50);

            var order = new BLL.CRM_order();
            DataSet dsorder = order.GetList("id=" + int.Parse(orderid));

            model.order_id = int.Parse(orderid);
            if (dsorder.Tables[0].Rows.Count > 0)
            {
                model.Customer_id = int.Parse(dsorder.Tables[0].Rows[0]["Customer_id"].ToString());
            }

            model.C_depid = int.Parse(request["T_dep_val"]);
            model.C_empid = int.Parse(request["T_employee_val"]);

            model.invoice_amount = decimal.Parse(request["T_invoice_amount"]);
            model.invoice_date = DateTime.Parse(request["T_invoice_date"]);
            model.invoice_type_id = int.Parse(request["T_invoice_type_val"]);
            model.invoice_content = PageValidate.InputText(request["T_content"], int.MaxValue);

            string cid = PageValidate.InputText(request["invoiceid"], 50);
            if (PageValidate.IsNumber(cid))
            {
                model.id = int.Parse(cid);

                DataSet ds = invoice.GetList(" id=" + model.id);
                DataRow dr = ds.Tables[0].Rows[0];

                invoice.Update(model);

                //日志
                var log = new sys_log();

                int UserID = emp_id;
                string UserName = emp_name;
                string IPStreet = request.UserHostAddress;
                string EventTitle = model.invoice_num;
                string EventType = "开票修改";
                int EventID = model.id;
                string Log_Content = null;

                if (dr["invoice_amount"].ToString() != request["T_invoice_amount"].Replace(",", "").Replace(".00", ""))
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "发票总额", dr["invoice_amount"],
                        request["T_invoice_amount"].Replace(",", "").Replace(".00", ""));

                if (dr["invoice_type"].ToString() != request["T_invoice_type"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "发票类型", dr["invoice_type"],
                        request["T_invoice_type"]);

                if (dr["invoice_num"].ToString() != request["T_invoice_num"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "发票号码", dr["invoice_num"],
                        request["T_invoice_num"]);

                if (dr["invoice_date"].ToString() != request["T_invoice_date"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "开票时间", dr["invoice_date"],
                        request["T_invoice_date"]);

                if (dr["invoice_content"].ToString() != request["T_content"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "开票内容", dr["invoice_content"],
                        request["T_content"]);

                if (dr["C_depname"].ToString() != request["T_dep"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "开票人部门", dr["C_depname"], request["T_dep"]);

                if (dr["C_empname"].ToString() != request["T_employee1"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "开票人姓名", dr["C_empname"], request["T_employee1"]);

                if (!string.IsNullOrEmpty(Log_Content))
                    log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, Log_Content);
            }
            else
            {
                model.isDelete = 0;
                model.create_id = emp_id;
                model.create_date = DateTime.Now;

                invoice.Add(model);
            }
            //更新订单发票金额
            order.UpdateInvoice(int.Parse(orderid));
        }

        public string grid()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " id";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = " desc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = "1=1";
            string order_id = request["orderid"];

            if (PageValidate.IsNumber(order_id) )
                serchtxt += " and order_id=" + int.Parse(order_id);

            if (!string.IsNullOrEmpty(request["company"]))
                serchtxt += $" and  customer_id in (select id from CRM_Customer where Customer like N'%{ PageValidate.InputText(request["company"], 255)}%')";

            if (!string.IsNullOrEmpty(request["receive_num"]))
                serchtxt += " and invoice_num like N'%" + PageValidate.InputText(request["receive_num"], 255) + "%'";

            if (!string.IsNullOrEmpty(request["pay_type"]))
                serchtxt += " and invoice_type_id =" + int.Parse(request["pay_type_val"]);

            if (!string.IsNullOrEmpty(request["department"]))
                serchtxt += " and C_depid =" + int.Parse(request["department_val"]);

            if (!string.IsNullOrEmpty(request["employee"]))
                serchtxt += " and C_empid =" + int.Parse(request["employee_val"]);

            if (!string.IsNullOrEmpty(request["startdate"]))
                serchtxt += " and invoice_date >= '" + PageValidate.InputText(request["startdate"], 255) + "'";

            if (!string.IsNullOrEmpty(request["enddate"]))
            {
                DateTime enddate = DateTime.Parse(request["enddate"]);
                serchtxt += " and invoice_date  <= '" +
                            DateTime.Parse(request["enddate"]).AddHours(23).AddMinutes(59).AddSeconds(59) + "'";
            }
            if (!string.IsNullOrEmpty(request["startdate_del"]))
            {
                serchtxt += " and Delete_time >= '" + PageValidate.InputText(request["startdate_del"], 255) + "'";
            }
            if (!string.IsNullOrEmpty(request["enddate_del"]))
            {
                DateTime enddate = DateTime.Parse(request["enddate_del"]).AddHours(23).AddMinutes(59).AddSeconds(59);
                serchtxt += " and Delete_time  <= '" + enddate + "'";
            }
            //权限
            DataSet ds = invoice.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);

            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);
            return (dt);
        }

        public string form(string id)
        {
            string dt;
            if (PageValidate.IsNumber(id))
            {
                DataSet ds = invoice.GetList("id=" + id);
                dt = DataToJson.DataToJSON(ds);
            }
            else
            {
                dt = "{}";
            }

            return (dt);
        }

        //del
        public string del(int id)
        {
            DataSet ds = invoice.GetList("id=" + id);

            bool isdel = invoice.Delete(id);

            //更新订单发票金额
            var order = new BLL.CRM_order();
            string orderid = ds.Tables[0].Rows[0]["order_id"].ToString();
            order.UpdateInvoice(int.Parse(orderid));

            if (isdel)
            {
                //日志
                string EventType = "开票删除";

                int UserID = emp_id;
                string UserName = emp_name;
                string IPStreet = request.UserHostAddress;
                int EventID = id;
                string EventTitle = ds.Tables[0].Rows[0]["Customer_name"].ToString();

                var log = new sys_log();

                log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, null);

                return ("true");
            }
            return ("false");
        }
    }
}